//
//  NewImgView.m
//  NewPro
//
//  Created by RYX on 2019/4/18.
//  Copyright © 2019 何荧红. All rights reserved.
//

#import "NewHomeImgView.h"
#import "NewHomeTopBtnCell.h"
#import "NewHomeServiceModel.h"
#import "HomeList.h"
#import "HomeBanner1.h"
#import "CreditCardDetailViewController.h"

@interface NewHomeImgView ()
{
    NSString *url;
    NSString *title;
}

@property (nonatomic,strong) UIImageView *bgIm;

@end

@implementation NewHomeImgView

- (instancetype)initWithFrame:(CGRect)frame{
    
    if (self = [super initWithFrame:frame]) {
        
        [self setUI];
        
    }
    return self;
}

- (void)setUI{
    
    UIImageView *bgIm = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, self.height)];
    self.bgIm = bgIm;
    bgIm.image = [self getDocumentImage];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onImg)];
    bgIm.userInteractionEnabled = YES;
    [bgIm addGestureRecognizer:tap];
    [self addSubview:bgIm];

    [bgIm mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.bottom.top.equalTo(self);        
    }];
    
}

- (void)setModel:(HomeBanner1 *)model{
    
    url = model.url;
    title = model.activityName;
    self.bgIm.image = [self getDocumentImage];
    [self.bgIm sd_setImageWithURL:[NSURL URLWithString:model.banner] placeholderImage:[self getDocumentImage]];
    
    dispatch_queue_t serialQueue = dispatch_queue_create("myThreadQueue", DISPATCH_QUEUE_SERIAL);
    dispatch_async(serialQueue, ^{
        
        UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:model.banner]]];
        [self saveImageDocuments:img];
    });
}

- (void)onImg{
    
    if (url.length <= 0) {
        
        return;
    }
    
    CreditCardDetailViewController *VC = [[CreditCardDetailViewController alloc]init];
    VC.url = url;
    [VC setNavBarWithTitle:title];
    [VC setHidesBottomBarWhenPushed:YES];
    [[self getCurrentViewController].navigationController pushViewController:VC animated:YES];
}

#pragma mark - 将顶部图片缓存到沙盒
-(void)saveImageDocuments:(UIImage *)image{
    //拿到图片
    UIImage *imagesave = image;
    NSString *path_sandox = NSHomeDirectory();
    //设置一个图片的存储路径
    NSString *imagePath = [path_sandox stringByAppendingString:@"/Documents/firstTopImg.png"];
    //把图片直接保存到指定的路径（同时应该把图片的路径imagePath存起来，下次就可以直接用来取）
    [UIImagePNGRepresentation(imagesave) writeToFile:imagePath atomically:YES];
    
}

#pragma mark - 读取沙盒图片
-(UIImage *)getDocumentImage{
    // 读取沙盒路径图片
    NSString *aPath3=[NSString stringWithFormat:@"%@/Documents/%@.png",NSHomeDirectory(),@"firstTopImg"];
    // 拿到沙盒路径图片
    UIImage *imgFromUrl3=[[UIImage alloc]initWithContentsOfFile:aPath3];
    return imgFromUrl3;
}

@end
